﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Prism.ViewModel;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Commands;
using System.ServiceModel.DomainServices.Client;
using UI.Web.SL.Demo.Infrastructure.Events;
using SailHero.Soft.FrameWork.Models;
using UI.Web.SL.Demo.RIAServices.Web;

namespace UI.Web.SL.Demo.Modules.Customer
{
    [Export(typeof(AddCustomerViewModel))]
    public class AddCustomerViewModel : NotificationObject
    {
        private IEventAggregator _eventAggregator;
        private ICommand _addCustomerCommmand;
        private CustomerDContext _customerDContext = new CustomerDContext();
        private CUSTOMER _customer;

        [ImportingConstructor]
        public AddCustomerViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            this.Customer = new CUSTOMER();
        }

        public CUSTOMER Customer
        {
            get { return _customer; }
            set
            {
                _customer = value;
                base.RaisePropertyChanged("Customer");
            }
        }

        public ICommand AddCustomerCommmand
        {
            get
            {
                if (_addCustomerCommmand == null)
                    _addCustomerCommmand = new DelegateCommand(AddCustomer);

                return _addCustomerCommmand;
            }
        }

        private void AddCustomer()
        {
            //CUSTOMER custm = new CUSTOMER() {AGE = 20, NAME = "admin", ID = 1222};
            _customerDContext.CUSTOMERs.Add(this.Customer);
            //_customerDContext.CUSTOMERs.Add(custm);
            _customerDContext.SubmitChanges(AddCustomerCompleted, null);
        }

        private void AddCustomerCompleted(SubmitOperation operation)
        {
            if (operation.IsComplete)
            {
                //发出添加Customer完成通知
                _eventAggregator.GetEvent<AddCustomerCompletedEvent>().Publish(null);

                //通知日志
                _eventAggregator.GetEvent<LoggingEvent>().Publish(
                    string.Format("添加Customer：Name={0},Age={1}", this.Customer.NAME, this.Customer.AGE));

                this.Customer = new CUSTOMER();
            }
        }
    }
}
